/*
* Wind Yao & Jacye Ouyang 20100131
*/
if (!Util){
    var Util = {};
}
Util.winSettingPanel = function(container){
    this.settingPN = $(document.createElement('div')).addClass('rtq-window-setpn').html('<div class="wrap"><h4><a href="javascript:void(0)" class="close">X</a>'+QS_Lang.workspace["win_setting"]+'</h4><div class="ctn"></div></div><div class="rtq-window-setpn-ft"><div class="ft-inner"></div></div><div class="rtq-window-setpn-mask"></div>').hide().appendTo(container);
    this.settingPNMask = this.settingPN.find('.rtq-window-setpn-mask');
	this.settingPN.find('h4 a.close').bind("click.win-setting",this,function(e){
        var sf = e.data;
        sf.settingPN.hide();
    });
    this.hide = function(){
        this.settingPN.hide()
    };
    this.reAlignSettingPN = function(cfg){
        var leftMargin = cfg.left;
        var rightMargin = $('body').width()-cfg.width-cfg.left;
        var pnWidth = this.settingPN.width();
        this.settingPN.css({
            'top':cfg.top,
            'left':(rightMargin>=pnWidth)?cfg.left+cfg.width+4:((leftMargin>=pnWidth)?cfg.left-pnWidth-10:cfg.left),
            'z-index':(rightMargin>=pnWidth)?((5-1)*100+1):(5*100+1) //edited by Wind @ 20120406, for this bug: QS-1016, 5 = WindowGroup.maxIndex, setting panel should cover other windows, but should not cover the elements in its own window. Updated by Wind @2012-05-02, for this bug: QS-1377. The setting panel should cover window when it left to the window
        });
    };
    //public function
    this.setVisibility = function(){
        if(this.settingPN.css('visibility') == 'hidden'){
            this.settingPN.css('visibility','visible');
        }
    };
    this.setHidden = function(){
        if(this.settingPN.css('visibility') != 'hidden'){
            this.settingPN.css('visibility','hidden');
        }
    };
    this.toggleDisplay = function(){
        this.settingPN.toggle();
    };
	this.setEnabled = function(){
		this.settingPN.removeClass('rtq-window-setpn-disabled');
    };
	this.setDisabled = function(){
		this.settingPN.addClass('rtq-window-setpn-disabled');
	};
    this.onOpenSettingPN = function(e){};
    this.hideSettingPN = function(){this.settingPN.hide();};
    this.showSettingPN = function(){this.settingPN.show();this.reAlignSettingPN();this.onOpenSettingPN();};
    this.addtoSettingPN = function(dom){this.settingPN.find('div.ctn').append(dom);};
    this.configSettingPN = function(obj){
        if(obj&&obj.width){
            this.settingPN.find('div.ctn').css('width',obj.width);
        }
        if(obj&&obj.height){
            this.settingPN.find('div.ctn').css('height',obj.height);			
        }
    };
    this.getSettingPNctn = function(){return this.settingPN.find('div.ctn')[0];};
    this.addClassToSettingPN = function(cls){this.settingPN.addClass(cls);};
    this.clear = function(){
        this.settingPN.unbind(".win-setting");
        this.settingPN.remove();
        for(var p in this){
        if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    }
}
/*window group*/
Util.WindowGroup=function(container,callback){
    var self=this;
    this.wins = [];
    this.winsObj=[];
    this.winsIndex=[];
    this.oContainer = typeof(container)== "string" ? $("#"+container):$(container);
    this.curWin=null;
    this.maxIndex = 5;
    var shadowCls = function(){
        this.shadowEl = $('<div class="rtq-win-shadow"><div class="ws-wrap"><div class="wins-west-north wins-conner"></div><div class="wins-east-north wins-conner"></div><div class="wins-east-south wins-conner"></div><div class="wins-west-south wins-conner"></div><div class="wins-south"></div><div class="wins-east"></div><div class="wins-west"></div></div></div>').appendTo(self.oContainer); 
        this.show = function(){
            this.shadowEl.show();
        };
        this.hide = function(){
            this.shadowEl.hide();
        };
        this.resize = function(cfg){
            var w=cfg.width;
            var h=cfg.height;
            var x=cfg.left;
            var y=cfg.top;
            var shadow=this.shadowEl;
            shadow.css({width:w+11,height:h,left:x-5,top:y+5,display:'block'}); 
            shadow.find('.wins-south').width(w-8);
            shadow.find('.wins-west,.wins-east').height(h-18);
        }    
    }
    this.shadow = new shadowCls();   
    var resizeProxyCls = function(){
        this.proxyEl=$('<div class="rtq-win-proxy"></div>').appendTo(self.oContainer);
        this.show = function(){
            this.proxyEl.show();
        };
        this.hide = function(){
            this.proxyEl.hide();
        };
        this.resize = function(cfg){        
            this.proxyEl.css({border:'1px dashed #999',position:'absolute',display:'block',zIndex:9999});
            if(typeof(cfg)!='undefined'){this.proxyEl.css(cfg);}
        };
        this.width=function(){
            return this.proxyEl.width();
        };
        this.height=function(){
            return this.proxyEl.height();
        };
        this.position=function(){
            return this.proxyEl.position();
        };
    }
    this.resizeProxy = new resizeProxyCls(); //  resize proxy object.
    var maskCls = function(){//added by wind 20100331 for iframe
        this.maskEl=$('<div class="rtq-win-mask"></div>').appendTo(self.oContainer);
        this.show = function(){
            this.maskEl.show();
        };
        this.hide = function(){
            this.maskEl.hide();
        };
        this.resize = function(cfg){
            this.maskEl.css({width:'100%',height:'100%',left:0,top:0,position:'absolute',display:'block',zIndex:9998,zoom:1,backgroundImg:'none'});
        };
        this.width=function(){
            return this.maskEl.width();
        };
        this.height=function(){
            return this.maskEl.height();
        };
        this.position=function(){
            return this.maskEl.position();
        };
    }
    this.maskProxy = new maskCls(); //  resize mask object.
};
Util.WindowGroup.prototype={
    register:function(win){
        if(win){
            win.winGroup = this;            
            if(win.cfg.layerIndex<0){
                win.cfg.layerIndex = 1;
                this.active(win);
            }
            if(win.cfg.active){
                this.active(win);
            }          
            this.wins.push(win);          
        }          
    },
    unregister:function(win){
        var flag = true ;
        var nextWin=0;
        for(var i=0;i<this.wins.length;i++){           
            if(this.wins[i] == win){
                this.wins.splice(i,1);
                i--;
            } else if(this.wins[i].layerIndex > 1){
                this.wins[i].cfg.layerIndex ++;
                this.wins[i].setIndex();
            } else if(this.wins[i].cfg.layerIndex == 1 && flag){
                this.wins[i].cfg.layerIndex ++;
                this.wins[i].setIndex();
                flag = false;
            }
        }
        for(var i=0;i<this.wins.length;i++){           
            if(parseInt(this.wins[i].cfg.layerIndex)>nextWin){
                nextWin=parseInt(this.wins[i].cfg.layerIndex);
            }
        }
        for(var i=0;i<this.wins.length;i++){      
            if(parseInt(this.wins[i].cfg.layerIndex)==nextWin){
                this.active(this.wins[i]);
                break;
            }
        }
    },
    active:function(win){
        var inx = win.cfg.layerIndex;
        win.active = true;
        for(var i=0;i<this.wins.length;i++){
            if(this.wins[i].cfg.layerIndex >= inx && this.wins[i].cfg.layerIndex > 1){
                this.wins[i].cfg.layerIndex --;
                this.wins[i].setIndex();
            }
            if(this.wins[i] != win){
                this.wins[i].onBlur(); // deactivate the window.
                this.wins[i].el.removeClass('rtq-win-active');
            }
        }
        win.cfg.layerIndex = this.maxIndex;
        win.setIndex();
        win.el.addClass('rtq-win-active');
        this.shadow.resize(win.cfg);
        this.curWin=win;
        this.shadow.shadowEl.css({zIndex:win.el.css('zIndex')-1});
    },
    refreshContainment:function(){
        if (!this.wins.length) {
            return false;
        }
        var wins=this.wins;
        for (var i = 0; i < wins.length; i++) {
            if(i==0){
                wins[i]._setDragContainment();
            }else{
                wins[i].dragContainment = wins[0].dragContainment;
            }
        }
    },
    setConfig:function(profile){
        if (!this.wins.length||!profile) {
            return false;
        }
        var wins=this.wins;
        for (var i = 0; i < wins.length; i++) {
            wins[i].setConfig(profile); 
        }
    }
};
/*window*/
//callbacks= {windowReady:function(){},beforeClosed:function(){},onResized:function(size){}}
Util.RtqWindow=function(container,callbacks,oConfig){   
    var self = this,qslang=QS_Lang.workspace;
    this.oContainer= typeof(container)== "string" ? $("#"+container):$(container);
    this.winGroup = null; 
    this.cfg = {
        title:qslang["win_dtitle"],
        width:450,
        height:300,
        autoResize:true, //contentObj can be resized with window
        resizable:true,
        closable:true,
        movable:true,
        disable:false,
        customCls:'',
        isGlobal:false, /* window type: global or not */
        hasSettingPanel:false,
        dragContainment :"document",  // "document", "window" or "Dom container"
        minWidth:250, //the window's min width
        minHeight:200, //the window's min height
        titleHeight:26,
        closeAction:'remove',//window close switcher
        state:1,// 0: min 1: normal 2:max. 
        layerIndex:-1,
        dragMethod:0,//0:display 1:hidden 2:position hide content when window was been drag,
        gridUnit:1,
        lineWidth:5,
        everyStep:false,
		locked:false,
		resizeOnDragStop:false,
        modal:false
    }; 
    this.dragContainment = [];
    this.clickOffset = {  // the position of the click point when mouse down relative to the window.
        left:0,
        top:0
    };
    this.curResizeHandlePos = {};   //
    this._curResizeHandle = '';
    this.callbacks = callbacks||{}; 
    this.oHTML='<div id="" class="rtq-win">'+
               '<div class="rtq-win-wrap">'+
               '<div class="win-hd"><h3 title=""><span>'+qslang["win_dtitle"]+'</span></h3><div class="win-operator"><div class="setting">'+qslang["win_medit"]+'</div><div class="max"></div><div class="close"></div></div></div>'+
               '<div class="win-bd"></div>'+
               '<div class="win-ft"></div>'+
               '<div class="win-north win-line win-resize"></div><div class="win-east win-line win-resize"></div><div class="win-south win-line win-resize"></div><div class="win-west win-line win-resize"></div>'+
               '<div class="win-west-north win-conner win-resize"></div><div class="win-east-north win-conner win-resize"></div><div class="win-east-south win-conner win-resize"></div><div class="win-west-south win-conner win-resize"></div>'+
               '</div>'+
               '<div class="rtq-win-tools"></div>'+
               '<div class="rtq-win-disable"></div>'+
			   '<div class="rtq-win-bd-mask"></div>'+
               '</div>';   
    this.el;    
    this.contentEl;
    this.titleContainer;  // 
    this.toolPanel;
	this.contentMask=null;
    this.mapResizeEl = ["n","e","s","w","wn","en","es","ws"];
    if(oConfig) {
        $.extend(this.cfg, oConfig);
    };
    this.cfg.oldBox={width:this.cfg.width,height:this.cfg.height,left:0,top:0};//kidy 20120525 the window when maxmize to minmize can't restore the before width/height
    this.title = this.cfg.title;
    this.active = this.cfg.active||false; // indicate the window is or not active.
    this.state = this.cfg.state;// 0 min 1: normal 2:max.    
    
    this.settingPanelObj = null;
    this._dragWinStarted = false;
    this._resizeWinStarted = false;
    this._dragTimeout = null;
    this._closed=false;
    this.init();    
};
Util.RtqWindow.prototype={
    init:function(content){
        var self = this;
        /* create window */        
        this.el = $(this.oHTML).attr({"id":this.id}).appendTo(this.oContainer);
        this.resizeHandler=$('.win-resize',this.el);
        this.disableDom = this.el.find('.rtq-win-disable');
        this.titleEl = this.el.find('div.win-hd');
        this.operatorEl=this.titleEl.find('div.win-operator');
        this.contentEl=this.el.find('div.win-bd');
		this.contentMask=this.el.find('.rtq-win-bd-mask');
        this.contentEl.attr('unselectable','on');
        
        this.toolPanel=this.el.find('.rtq-win-tools').eq(0); 
                       
        this.el.bind('click.win',this,this._onFocus);
        
        
        this.titleEl.bind('mousedown.win',this,this._dragStart); // bind event to title.
//        this.titleEl.bind('select.win',this,function(){return false;});
//        this.titleEl.attr('unselectable', 'on');
        
        
        
        if(this.cfg.resizable){
            this.resizeHandler = $('.win-resize',this.el).each(
                function(i){
                  $(this).data("index.resize",self.mapResizeEl[i])
                  if($.browser.msie){   
                    $(this).attr('unselectable', 'on');
                  }
                }
            );
            this.resizeHandler.bind('mousedown.win',this,this._resizeStart); 
            this.titleEl.bind('dblclick.win',this,this.dblClickWindow);
        }else{
            $('.win-resize',this.el).css({cursor:'default'});
            $('.max',this.el).css({display:'none'});
        }
        
        if(this.cfg.closable==false){
            $('.close',this.el).css({display:'none'});
        }
        this.setLock(this.cfg.locked);      
                
        $(".win-operator",this.el).bind("click.win",this,this.operateWin);        
        if(this.cfg.hasSettingPanel){
            this.settingPanelObj = new Util.winSettingPanel(this.oContainer);
        }else{
            $('.setting',this.el).hide();
        }
        this._setDragContainment();
        var cX=(this.oContainer.width()-this.cfg.width)/2;
        var cY=(this.oContainer.height()-this.cfg.height)/2;
        this.cfg.left = Math.max(this.cfg.left==undefined?cX:this.cfg.left, this.dragContainment[0]);
        this.cfg.top = Math.max(this.cfg.top==undefined?cY:this.cfg.top, this.dragContainment[1]);
		
		this.cfg.oldBox.width = this.cfg.oldBox.width||this.cfg.width;
		this.cfg.oldBox.height = this.cfg.oldBox.height||this.cfg.height;
		this.cfg.oldBox.top = this.cfg.oldBox.top||this.cfg.top;
		this.cfg.oldBox.left = this.cfg.oldBox.left||this.cfg.left;
        
		this._setWin();
        
        if(typeof(this.callbacks.windowReady)== "function"){ // init component in window content
            this.callbacks.windowReady(self);
        }
		if (this.cfg.title.indexOf(": ") == -1) {
			this.setTitle(this.cfg.title);
		} else {
			this.setTitle(this.cfg.title.substr(0, this.cfg.title.indexOf(": ")));
		}
        if(this.cfg.state==2){
            this.maxmize();      
        }       
        if (this.cfg.layerIndex>-1) {
            this.setIndex();
        }                           
    },
    operateWin:function(e){
        var self = e.data;
        self.winGroup.active(self);
        var tar = $(e.target);
        if(tar.hasClass("close")){ 
            if(typeof(self.callbacks.beforeClosed)== "function"){
                self.callbacks.beforeClosed(self);
            }
            if(self.cfg.closeAction=='hide'){
                self.hide.call(self);   // hide the object.
            }else if(self.cfg.closeAction=='remove'){
                self.clear.call(self);   // destory the object. 
            }            
        }else if(tar.hasClass("max")){            
            self.maxmize.call(self);
        }else if(tar.hasClass("restore")){           
            self.restore.call(self);
        }else if(tar.hasClass("setting")&& self.settingPanelObj != null){ // click the settingPanel
            self.settingPanelObj.reAlignSettingPN(self.cfg);
            self.settingPanelObj.setVisibility();
            self.settingPanelObj.toggleDisplay();
            if(self.settingPanelObj.onOpenSettingPN){self.settingPanelObj.onOpenSettingPN();}
        }else if(tar.hasClass('ipt_symbol')){tar.focus();}
        //e.stopImmediatePropagation();
        //return false;
    },
    dblClickWindow:function(e){
        var self = e.data;
        var target = $(e.target);
        if(target.hasClass("win-operator") || target.parent().hasClass("win-operator")){  // click on operator.
            return false;
        }else if(target.hasClass("ipt_symbol",self.el)){
        }else{
            if(self.cfg.state == 1){
                self.maxmize();
            }else if(self.cfg.state == 2){
                self.restore();
            }
        }       
    },
    maxmize:function(){
//		if(this.cfg.locked==true){
//            return false;
//        }       
        var win=this.el;
        var panel=this.oContainer;
        var size = {width:panel.width(),height:panel.height(),top:0,left:0};
        this.cfg.width = size.width, this.cfg.height = size.height, this.cfg.left = 0,this.cfg.top = 0;
        win.css(size);
        win.find('.rtq-win-wrap').css({
            width: size.width,
            height: size.height
        });
        $('.max',win).addClass('restore').removeClass('max');
        this.contentEl.css({width: size.width,height: size.height-26});
		this.contentMask.css({width: size.width+1,height: size.height-24});
        this.titleContainer.css({
            //width: this.cfg.width - this.operatorEl.width()-40
        });
        this.cfg.state=2;
        if(typeof(this.callbacks.onResized)== "function"){
            this.callbacks.onResized(this,size.width,size.height);
        } 
        if (this.settingPanelObj != null) {
            this.settingPanelObj.reAlignSettingPN(size);
            this.settingPanelObj.setVisibility();
        }
    },
    restore:function(){
//		if(this.cfg.locked==true){
//            return false;
//        }
        this.cfg.width = this.cfg.oldBox.width, this.cfg.height = this.cfg.oldBox.height;
        this.cfg.left = this.cfg.oldBox.left, this.cfg.top = this.cfg.oldBox.top;
        this.el.css(this.cfg.oldBox);
        this.el.find('.rtq-win-wrap').css({
            width: this.cfg.oldBox.width,
            height: this.cfg.oldBox.height
        });
        $('.restore',this.el).addClass('max').removeClass('restore');
        this.contentEl.css({width: this.cfg.oldBox.width,height: this.cfg.oldBox.height-26});
		this.contentMask.css({width: this.cfg.oldBox.width+1,height: this.cfg.oldBox.height-24});
        this.titleContainer.css({
            //width: this.cfg.width - this.operatorEl.width()-40
        });
        this.cfg.state=1;
        this.winGroup.shadow.resize(this.cfg.oldBox);
        if(typeof(this.callbacks.onResized)== "function"){
            this.callbacks.onResized(this,this.cfg.oldBox.width,this.cfg.oldBox.height);
        }
        if (this.settingPanelObj != null) {
            this.settingPanelObj.reAlignSettingPN(this.cfg);
            this.settingPanelObj.setVisibility();
        }
    },
    _dragContent:function(obj){
        switch(obj.cfg.dragMethod){
            case 0:
            obj.contentEl.hide();
            break;
            case 1:
            obj.contentEl.css({visibility:'hidden'});
            break;
            case 2:
            obj.contentEl.children().css({position:'absolute',left:'-1000px'});
            break;
            default:
            obj.contentEl.hide();
            break;
        } 
    },
    _dragStart:function(e){   // start to drag the window callback.              
        var target = $(e.target);
        var self = e.data;
        if(self.cfg.movable==false){return false;}
        if(e.which != 1 || target.hasClass("win-operator") || target.parent().hasClass("win-operator")||target.hasClass("ipt_symbol",self.el)||self.cfg.locked==true){  // click on operator.
            //return false;
        }else{
            e.preventDefault();
            if(!self.active){
                self.winGroup.active(self); // active the window.
            }
            if(self.cfg.state == 2){return false}  // maximum 
            (self._mouseStarted && self._dragStop(e));  // drag out of window. 
            var p = self.el.position();
            self.clickOffset.left =self._getXY(e).x-p.left;
            self.clickOffset.top = self._getXY(e).y-p.top; 
            $(document).bind('mousemove.RtqWindowDrag',self,self._dragMove);  
            $(document).bind('mouseup.RtqWindowDrag',self,self._dragStop);
            self._dragTimeout = setTimeout(function(){
                self._mouseStarted = true;
                self.winGroup.shadow.hide();
                self._dragContent(self);               
            },300);
            if (self.settingPanelObj != null) {
                self.settingPanelObj.setHidden();
            }
            window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();//avoid text selecting
        }        
    },
    _createDraggingPostion:function(e){
        e.preventDefault();//edited by wind yao 20100219
        if(this._mouseStarted) { //If we are not dragging yet, we won't check for options
            if(this.dragContainment) {
                if(e.pageX - this.clickOffset.left < this.dragContainment[0]) e.pageX = this.dragContainment[0] + this.clickOffset.left;
                if(e.pageY - this.clickOffset.top < this.dragContainment[1]) e.pageY = this.dragContainment[1] + this.clickOffset.top;
                if(e.pageX - this.clickOffset.left+20 > this.dragContainment[2]) e.pageX = this.dragContainment[2] + this.clickOffset.left-20;
                if(e.pageY - this.clickOffset.top +this.cfg.titleHeight > this.dragContainment[3]) e.pageY = this.dragContainment[3] + this.clickOffset.top-this.cfg.titleHeight;
            }
        }
        return {left:e.pageX-this.clickOffset.left,
                top:e.pageY-this.clickOffset.top};
    },
    _dragMove:function(e){
        e.preventDefault();//edited by wind yao 20100219        
        var self = e.data;        
        if(self._dragTimeout != null && !self._mouseStarted){
            clearTimeout(self._dragTimeout);
            self._dragTimeout = null;
            self._mouseStarted = true;
            self.winGroup.shadow.hide();
            self._dragContent(self);
        }
        var pos =  self._createDraggingPostion(e);
        if(self.cfg.gridUnit>1&&self.cfg.everyStep){
            self._fnSnapToGrid(pos);
        }else{
            self.cfg.left = self.cfg.oldBox.left = pos.left;             
            self.cfg.top = self.cfg.oldBox.top = pos.top;
        }
        if(typeof(pos)!='undefined'){self.el.css(pos);}
        window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();//avoid text selecting
    },
    _dragStop:function(e){
        var self = e.data;
        if (self._dragTimeout != null) {
            clearTimeout(self._dragTimeout);
            self._dragTimeout = null;
        }
        //snap to grid
        var pos={}
        if(self.cfg.gridUnit>1&&!self.cfg.everyStep){
            self._fnSnapToGrid(pos);
        }            
        self.el.css(pos);
                
        $(document).unbind("mousemove.RtqWindowDrag",self._dragMove); 
        $(document).unbind("mouseup.RtqWindowDrag",self._dragStop);      
        self.winGroup.shadow.resize(self.cfg);
        self.winGroup.shadow.shadowEl.css({zIndex:self.el.css('zIndex')-1});
        switch(self.cfg.dragMethod){
            case 0:
            self.contentEl.show();
            break;
            case 1:
            self.contentEl.css({visibility:'visible'});
            break;
            case 2:
            self.contentEl.children().css({position:'static'});
            break;
            default:
            self.contentEl.show();
            break;
        } 
        if (self.settingPanelObj != null) {
            self.settingPanelObj.reAlignSettingPN(self.cfg);
            self.settingPanelObj.setVisibility();
        }
		if(typeof(self.callbacks.onResized)== "function"&&self.cfg.resizeOnDragStop==true&&self._mouseStarted==true){
            self.callbacks.onResized(self,self.cfg.width,self.cfg.height);
        }
		self._mouseStarted = false;
        window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();//avoid text selecting
    },
    _changeSize: {
        n:function(e,oCfg,ePos,self){
            var eY=self._getXY(e).y-ePos.dy;
            var cH=oCfg.height+oCfg.top-eY;
            var minHeight=self.cfg.minHeight;
            cH=cH<minHeight?minHeight:cH;
            if(cH>minHeight){
                return {height:cH,top:eY};
            }else{}
        },
        e:function(e,oCfg,ePos,self){
            var cW=oCfg.width+self._getXY(e).x-ePos.x;
            var minWidth=self.cfg.minWidth;
            cW=cW<minWidth?minWidth:cW;
            return {width: cW};
        },
        s:function(e,oCfg,ePos,self){
            var cH=oCfg.height+self._getXY(e).y-ePos.y;
            var minHeight=self.cfg.minHeight;
            cH=cH<minHeight?minHeight:cH;
            return {height:cH};
        },
        w:function(e,oCfg,ePos,self){
            var eX=self._getXY(e).x-ePos.dx;
            var cW=oCfg.width+oCfg.left-eX;
            var minWidth=self.cfg.minWidth;
            cW=cW<minWidth?minWidth:cW;
            if(cW>minWidth){
                return {width:cW,left:eX};
            }else{}            
        },
        wn:function(e,oCfg,ePos,self){
            var eX=self._getXY(e).x-ePos.dx;
            var eY=self._getXY(e).y-ePos.dy;
            var cW=oCfg.width+oCfg.left-eX;
            var cH=oCfg.height+oCfg.top-eY;
            var minWidth=self.cfg.minWidth;
            var minHeight=self.cfg.minHeight;
            cW=cW<minWidth?minWidth:cW;
            cH=cH<minHeight?minHeight:cH;
            
            if(cW>minWidth&&cH>minHeight){
                return {width:cW,height:cH,left:eX,top:eY};
            }else if(cW>minWidth&&cH==minHeight){
                return {width:cW,left:eX};
            }else if(cW==minWidth&&cH>minHeight){
                return {height:cH,top:eY};
            }else{return{};}
        },
        en:function(e,oCfg,ePos,self){
            var eY=self._getXY(e).y-ePos.dy;
            var cW=oCfg.width+self._getXY(e).x-ePos.x;
            var cH=oCfg.height+oCfg.top-eY;
            var minWidth=self.cfg.minWidth;
            var minHeight=self.cfg.minHeight;
            cW=cW<minWidth?minWidth:cW;
            cH=cH<minHeight?minHeight:cH;
            if(cH>minHeight&&cW>minWidth){
                return {width:cW,height:cH,top:eY};
            }else if(cH>minHeight&&cW==minWidth){
                return {height:cH,top:eY};
            }else if(cH==minHeight&&cW>minWidth){
                return {width:cW};
            }else{return{};}                  
        },
        es:function(e,oCfg,ePos,self){
            var cW=oCfg.width+self._getXY(e).x-ePos.x;
            var cH=oCfg.height+self._getXY(e).y-ePos.y;
            var minWidth=self.cfg.minWidth;
            var minHeight=self.cfg.minHeight;
            cW=cW<minWidth?minWidth:cW;
            cH=cH<minHeight?minHeight:cH;
            return {width:cW,height:cH};
        },
        ws:function(e,oCfg,ePos,self){
            var eX=self._getXY(e).x-ePos.dx;
            var cW=oCfg.width+oCfg.left-eX;
            var cH=oCfg.height+self._getXY(e).y-ePos.y;
            var minWidth=self.cfg.minWidth;
            var minHeight=self.cfg.minHeight;
            cW=cW<minWidth?minWidth:cW;
            cH=cH<minHeight?minHeight:cH;
            if(cW>minWidth&&cH>minHeight){
                return {width:cW,height:cH,left:eX};
            }else if(cW==minWidth&&cH>minHeight){                
                return {height:cH};               
            }else if(cW>minWidth&&cH==minHeight){
                return {width:cW,left:eX};
            }else{return{};}        
        }
    },
    _resizeStart:function(e){  // start to resize the window. 
        //proxy of window
        e.preventDefault();    
        var self = e.data;
        self._curResizeHandle = $(e.target).data("index.resize");
        if(e.which != 1 || self.cfg.state == 2 || self.cfg.locked==true){// right mouse down and maxmize window.
            return false
        }
        self.winGroup.resizeProxy.resize(self.cfg);
        self.winGroup.maskProxy.resize(self.cfg);      
        self.curResizeHandlePos = {
            x:self._getXY(e).x, y:self._getXY(e).y,
            dx:self._getXY(e).x-self.cfg.left, dy:self._getXY(e).y-self.cfg.top
        };
        self.winGroup.shadow.hide();        
        $(document).bind('mousemove.RtqWindowResize',self,self._resizeMove);
        $(document).bind('mouseup.RtqWindowResize',self,self._resizeStop);
        
        return false;//avoid text selecting
    },  
    _resizeMove:function(e){ // resizing window 
        e.preventDefault();//edited by wind yao 20100219
        var self = e.data;
        if ($.browser.msie && !e.which) {  // ie out of window. edited by wind 20110701 to fix a bug in IE9
            return self._resizeStop(e);
        }
        var cs = self._changeSize[self._curResizeHandle].apply(this,[e,self.cfg,self.curResizeHandlePos,self]);
        
        //step by step snap to grid
        if(self.cfg.gridUnit>1&&self.cfg.everyStep){
            self._fnSnapToGrid(cs,'');
        }
        self.winGroup.resizeProxy.resize(cs);       
        return false;//avoid text selecting
    },
    _resizeStop:function(e){  // stop resize window.
        var self = e.data;
        $(document).unbind('mousemove.RtqWindowResize',self._resizeMove);
        $(document).unbind('mouseup.RtqWindowResize',self._resizeStop);
        self.cfg.oldBox.width = self.cfg.width = self.winGroup.resizeProxy.width();
        self.cfg.oldBox.height = self.cfg.height = self.winGroup.resizeProxy.height();
        var XY=self.winGroup.resizeProxy.position();
        self.cfg.oldBox.left = self.cfg.left= XY.left;
        self.cfg.oldBox.top = self.cfg.top= XY.top;
        self.cfg.zindex=self.cfg.layerIndex*100;
        var ps={left:XY.left,top:XY.top,width:self.cfg.width,height:self.cfg.height,zindex:self.cfg.zindex};
        
        if(self.cfg.gridUnit>1&&!self.cfg.everyStep){
            self._fnSnapToGrid(ps);
        }
        
        self.el.css(ps).find('.rtq-win-wrap').css({   // change the wrap div size
            width: self.cfg.width,
            height: self.cfg.height
        });
        self.contentEl.css({width: self.cfg.width,height: self.cfg.height-26}); // change the content container size.
        self.contentMask.css({width: self.cfg.width+1,height: self.cfg.height-24}); // change the loading mask size.
        if(self.loadingEl){
			self.loadingEl.width(self.cfg.width-self.operatorEl.width());
		}
		self.winGroup.shadow.resize(self.cfg);
        self.winGroup.shadow.shadowEl.css({zIndex:self.el.css('zIndex')-1});
        self.winGroup.resizeProxy.hide();
        self.winGroup.maskProxy.hide();
        if (self.settingPanelObj != null) {
            self.settingPanelObj.reAlignSettingPN(self.cfg);
            self.settingPanelObj.setVisibility();
        }
        if(typeof(self.callbacks.onResized)== "function"){
            self.callbacks.onResized(self,self.cfg.width,self.cfg.height);
            self.titleContainer.css({
               // width: self.cfg.width - self.operatorEl.width()-40
            });
        }
        return false;
    },
    _setDragContainment: function() {  // set the drag containment
        var o = this.cfg;
        if(o.dragContainment == 'document' || o.dragContainment == 'window') this.dragContainment = [
            0 ,   //left
            0 ,   //top.
            $(o.dragContainment == 'document' ? document : window).width() ,
            ($(o.dragContainment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight)
        ];

        if(!(/^(document|window)$/).test(o.dragContainment) && o.dragContainment.constructor != Array) {  // Dom element
            var ce = $(o.dragContainment)[0]; if(!ce) return;
            var co = $(o.dragContainment).offset();
            var over = ($(ce).css("overflow") != 'hidden');

            this.dragContainment = [
                (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0),
                (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) ,
                (over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) ,
                (over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) 
            ];
        } else if(o.dragContainment.constructor == Array) {
            this.dragContainment = o.dragContainment;
        }
    },
    _fnSnapToGrid:function(profile,proxyObj){
        if(!profile){
            profile={};
        }
        var config = this.cfg;
        var width = profile.width||config.width;
        var height = profile.height||config.height;
        var top = profile.top||config.top;
        var left = profile.left||config.left;
		var minWidth = profile.minWidth||config.minWidth;
		var minHeight = profile.minHeight||config.minHeight;
        var unit = profile.gridUnit||config.gridUnit;
        var lineWidth = config.lineWidth;
        var dragContainment = this.dragContainment;
        
        if(unit<1){
            return false;
        }
        //the width can not be less than the min-width
		//the height can not be less than the min-height        
		width=Math.round((width/unit),0)*unit-lineWidth;
		height=Math.round((height/unit),0)*unit-lineWidth;		
        left=Math.round((left/unit),0)*unit+lineWidth;
        top=Math.round((top/unit),0)*unit+lineWidth;
		if(this._curResizeHandle=='n'){
            top=height<minHeight?top-unit:top;
		}else if(this._curResizeHandle=='wn'){
			left=width<minWidth?left-unit:left;
            top=height<minHeight?top-unit:top;
		}else if(this._curResizeHandle=='w'){
			left=width<minWidth?left-unit:left;
		}
		width=width<minWidth?width+unit:width;
        height=height<minHeight?height+unit:height;
        
        if(typeof proxyObj=='undefined'){            
            this.cfg.left = this.cfg.oldBox.left = profile.left = left>dragContainment[2]?left-unit:left;             
            this.cfg.top = this.cfg.oldBox.top = profile.top = top>dragContainment[3]?top-unit:top;
            if(profile.width){
                if(this._curResizeHandle=='e'||this._curResizeHandle=='en'||this._curResizeHandle=='es'){
                    this.cfg.width = this.cfg.oldBox.width = profile.width = width>dragContainment[2]-left-lineWidth?dragContainment[2]-left-lineWidth:width;
                }else if(this._curResizeHandle!='s'){
                    this.cfg.width = this.cfg.oldBox.width = profile.width = width;
                }
            }
            if(profile.height){
                if(this._curResizeHandle=='s'||this._curResizeHandle=='es'||this._curResizeHandle=='ws'){
                    this.cfg.height = this.cfg.oldBox.height = profile.height = height>dragContainment[3]-top-lineWidth?dragContainment[3]-top-lineWidth:height;
                }else if(this._curResizeHandle!='e'){
                    this.cfg.height = this.cfg.oldBox.height = profile.height = height;
                }
            }          
        }else{            
            profile.left = left>dragContainment[2]?left-unit:left;             
            profile.top = top>dragContainment[3]?top-unit:top;
            profile.width = width>dragContainment[2]-left-lineWidth?dragContainment[2]-left-lineWidth:width;
            profile.height = height>dragContainment[3]-top-lineWidth?dragContainment[3]-top-lineWidth:height;
        }
    },
    setConfig:function(profile){
        if(!profile){
            profile = {};
        }
        $.extend(this.cfg, profile);
    },
	setLock:function(bLock, closable){
		if(typeof bLock=='undefined'){
			bLock=true;
		}
		this.cfg.locked=bLock;
		
		if (bLock&&(typeof(closable) == 'undefined' || closable != true)){
			this.el.addClass('rtq-win-locked');
		}else{
			this.el.removeClass('rtq-win-locked');
		}
	},
    _getXY:function(e){
        var self=e.data;
        if(e.pageX||e.pageY){
            return {x:e.pageX,y:e.pageY}
        }else{
            return {x:e.pageX+document.body.scrollLeft-document.body.clientLeft,y:e.pageY+document.body.scrollTop-document.body.clientTop}                    
        }
    },
	_setSettinpPanel:function(profile){
		if (this.settingPanelObj != null) {
            this.settingPanelObj.reAlignSettingPN({width:w,height:h,top:0,left:0});
            this.settingPanelObj.setVisibility();
        }
	},
    _setSize:function(w,h){
		this.el.css({width:w,height:h});
        this.contentEl.css({width:w,height:h-26});
		this.contentMask.css({width:w+1,height:h-24}); 
        this.cfg.width = w;
        this.cfg.height = h;
    },
	setSize:function(w,h){
		//no one use it
        this._setSize(w,h);
        if(typeof(this.callbacks.onResized)== "function"){
            this.callbacks.onResized(this,w,h);
        } 
        if (this.settingPanelObj != null) {
            this.settingPanelObj.reAlignSettingPN({width:w,height:h,top:0,left:0});
            this.settingPanelObj.setVisibility();
        }
    },
	_setWin:function(){
        this.el.css(this.cfg);
        this.contentEl.css({
            width: this.cfg.width,
            height: this.cfg.height - 26
        });
		this.contentMask.css({
            width: this.cfg.width+1,
            height: this.cfg.height - 24
        });
        this.titleContainer = this.titleEl.find('h3 span').attr("title",this.title);
        if(this.settingPanelObj != null){
            this.settingPanelObj.reAlignSettingPN(this.cfg);
            this.settingPanelObj.setVisibility(); 
        }		
    },
	setToGrid:function(profile){
        //Initial size to grid
        if(this.cfg.gridUnit>1&&this.cfg.state!=2&&profile.id<0&&profile.id>-10000){
            this._fnSnapToGrid(this.cfg);
			var w=this.cfg.width,h=this.cfg.height;
	        this._setWin();
	        this.winGroup.shadow.resize(this.cfg);
	        if(typeof(this.callbacks.onResized)== "function"){
	            this.callbacks.onResized(this,w,h);
	        }	        
        }else{
			return false;
		}		
    },
    _onFocus:function(e){
        var self=e.data;
        if(!self.active&&self._closed==false){
			if(self.winGroup){
				self.winGroup.active(self);
			}
            if (self.settingPanelObj != null && self.cfg.state != 2) {
                self.settingPanelObj.reAlignSettingPN(self.cfg); // set position of setting panel.
            }
        }      
    },
    setTitle:function(title,ticker,cfg){
		var needReplace=true;
		if (typeof(cfg) != "undefined" && typeof(cfg.needReplace) != "undefined") {
			needReplace=cfg.needReplace===false?false:true;
		}
		if(typeof(ticker)=="string"&&typeof(ticker)!="undefined"&&needReplace){
				ticker=ticker.replace("/",".");
		}
		if(typeof(cfg)!="undefined"&&typeof(cfg.boxHide)!="undefined"&&cfg.boxHide){
			this.title = title+ticker;
			title =  title+ticker;
			this.titleContainer.text(title);//updated at 20100625
        	this.titleContainer.attr({title:title});
		}else{
			this.title = title+(typeof(ticker)=="undefined"||ticker==false?"":" "+ticker);
			this.titleContainer.text(title.replace(":",""));//updated at 20100625
        	this.titleContainer.attr({title:title});
		}
    },  
    getTitle:function(){
        return this.title;
    },   
    resetSize:function(size){
        this._setSize(size.width,size.height);
    },   
    onBlur:function(){  // deactivate the window
        if (this.settingPanelObj != null) {
            this.settingPanelObj.hide();
        }
        this.active = false;
        this.winGroup.shadow.hide();        
    },
    setHtml:function(content){
        if(typeof(content)=='string'){
            this.contentEl.html(this.contentEl.html()+content);
        }else{
            this.contentEl.append(content);
        }        
    },
    setIndex:function(){
        var NumIndex=this.cfg.isGlobal?200:100;
        if(this.cfg.layerIndex > 0){
            this.el.css({zIndex:this.cfg.layerIndex*NumIndex});
            this.cfg.zindex=this.cfg.layerIndex*NumIndex;
        }
    },
	setPosition:function(x,y){
		if(typeof x=='undefined'||typeof y=='undefined'||typeof x==''||typeof y==''){
			return false;
		}
		this.cfg.left=x;
		this.cfg.top=y;
		this.el.css(this.cfg);
	},
    getIndex:function(){
        return this.cfg.layerIndex;
    },
    getState:function(){
        return this.cfg.state;
    },
    getActive:function(){
        return this.active;
    },
//    setMinWidth:function(w){
//        this.cfg.minWidth=w;
//    },
    disable:function(){//for detach window
        this.disableDom.show();
    },
    enable:function(){//for detach window
        this.disableDom.hide();
    },
    clear:function(){
        this.winGroup.unregister(this);
        this.winGroup.shadow.hide();
        this.winGroup = null;
        if (this.settingPanelObj != null) {
            this.settingPanelObj.clear();
        }
        this.el.find('.win-hd').unbind(".win");
        this.oContainer.unbind(".win");
        this.el.find(".win-operater").unbind(".win");
        this.el.unbind(".win");
        this.el.remove();
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    },
    show:function(){
        this.el.show();
        if(!this.active){
            this.winGroup.shadow.resize(this.cfg);
            this.winGroup.curWin=this.el;
            this.winGroup.active(this);
            this.winGroup.shadow.shadowEl.css({zIndex:this.el.css('zIndex')-1});
            if (this.settingPanelObj != null && this.cfg.state != 2) {
                this.settingPanelObj.reAlignSettingPN(this.cfg); // set postion of setting panel.
            } 
        }
    },
    hide:function(){
		//this.restore.call(this);
        this.el.hide();
        this._closed=true;
        this.onBlur();
    }
};